package com.hwpt.chesedemo.data.remote.util

import com.hwpt.chesedemo.presentation.component.Position


object ChessUtils {
    fun getAiDepth(aiLevel: Int): Int {
        return when (aiLevel) {
            1 -> 1  // 新手
            2 -> 3  // 入门
            3 -> 5  // 进阶
            4 -> 9  // 专家
            5 -> 12 // 大师
            else -> 3
        }
    }

    // 在 ChessUtils.kt 中
    fun parseStockfishMove(bestmove: String): Pair<Position, Position>? {
        return try {
            println("DEBUG: Parsing bestmove: $bestmove")

            // 处理 Stockfish 返回的完整格式: "bestmove e7e5 ponder c2c4"
            val movePattern = """bestmove\s+([a-h][1-8][a-h][1-8])""".toRegex()
            val matchResult = movePattern.find(bestmove)

            val moveString = if (matchResult != null) {
                // 从完整格式中提取移动部分
                matchResult.groupValues[1]
            } else {
                // 如果已经是纯移动字符串，直接使用
                bestmove.trim()
            }

            println("DEBUG: Extracted move string: $moveString")

            if (moveString.length != 4) {
                println("DEBUG: Invalid move string length: ${moveString.length}")
                return null
            }

            val fromFile = moveString[0]
            val fromRank = moveString[1]
            val toFile = moveString[2]
            val toRank = moveString[3]

            val from = algebraicToPosition("$fromFile$fromRank")
            val to = algebraicToPosition("$toFile$toRank")

            println("DEBUG: Parsed positions - from: $from, to: $to")

            if (from != null && to != null) {
                Pair(from, to)
            } else {
                println("DEBUG: Failed to convert algebraic notation")
                null
            }
        } catch (e: Exception) {
            println("DEBUG: Exception in parseStockfishMove: ${e.message}")
            null
        }
    }



    private fun algebraicToPosition(algebraic: String): Position? {
        if (algebraic.length != 2) return null

        val file = algebraic[0]
        val rank = algebraic[1]

        if (file !in 'a'..'h' || rank !in '1'..'8') return null

        val col = file - 'a'
        val row = 8 - (rank - '0')

        return Position(row, col)
    }
}